package cj.web.lkg.controllers;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import cj.utils.weixin.pay.Sign;
import cj.utils.weixin.pay.WXConfigUtil;

public class BaseController{
	private static Map<String,String> wxJSConfig;
	
    public Map<String, String> getConfigSign(HttpServletRequest request) throws Exception{
    	String ticket = "";
    	
    	if(null != wxJSConfig){
    		Long current =  Long.valueOf(System.currentTimeMillis() / 1000);
    		Long timestamp = Long.valueOf(wxJSConfig.get("timestamp").toString());
    		if( current - timestamp > 3600){
    			ticket = refreshTicket();
    		}
    		else{
    			ticket = wxJSConfig.get("jsapi_ticket").toString();
    		}
    	}
    	else{
    		ticket = refreshTicket();
    	}
    	
    	return getSign(request, ticket);
    }
    
    private String refreshTicket() throws Exception{
    	String appid = "wxca2b6479a04a738d";
		String secret = "1c1f6a4140bc70b3008bd3bfcaccb47e";
		String ticket = WXConfigUtil.returnJsapiTicket(appid, secret);
		
		return ticket;
    }

	private Map<String, String> getSign(HttpServletRequest request, String ticket) {
		String url = request.getScheme() +"://" + request.getServerName() + request.getServletPath();
	    if (request.getQueryString() != null){
	        url += "?" + request.getQueryString();
	    }
	    wxJSConfig= Sign.sign(ticket, url);
	    return wxJSConfig;
	}
    
}
